<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-07-31
 * Time: 18:32
 */
namespace app\index\controller;
use app\index\model\Staff;
class Softdel{


    //模型实例删除:delete( )
    public function index(){
        ///获取id=1002的模型实例,创建数据对象$data
        $data = Staff::get(1002);

        //删除当前数据对象
        $affected = $data->delete();

        //反馈执行结果
        echo $affected ? '成功的软删除了'.$affected.'条记录!' : '软删除失败~~';
    }
    //正常查询：不显示已软删除的记录
    public function index1()
    {
        //创建查询闭包函数
        $closure = function ($query){
            $query -> field('id,name,delete_time');
        };

        //执行查询
        $result = Staff::all($closure);

        foreach ($result as $data){
            dump($data->getData());
        }
    }
    //特殊查询：可以查看已被软删除掉的数据
    public function index2()
    {
        //用SoftDelete类的withTrashed() 方法实现
        $result = Staff::withTrashed()
            ->field('id,name,delete_time')   //设置查询条件
            -> select();     //输出结果集：对象数组

        //遍历对象数组
        foreach ($result as $data){

            //输出原始数据
            dump($data->getData());
        }
    }
    //静态软删除:destroy( )
    //一、根据主键或主键列表软删除

    public function index3(){
        //**任务1：**软删除主键id = 1002 的记录关键语句：
        Staff::destroy(1002,false);
        //**任务2：**软删除主键id = 1002,1003,1004 的记录关键语句：
        Staff::destroy([1002,1003,1004],false);

    }

    //二、根据查询条件软删除数据

    public function index4(){
        //软删除salary > 5000的记录
        $affected = Staff::destroy(['salary'=>['>',5000]],false);

        echo $affected ? '成功软删除'.$affected.'条记录!' : '软删除失败';

        //创建闭包查询函数
        $closure = function ($query){
            $query -> field('id,name,delete_time');
        };

        //执行查询
        $result = Staff::all($closure);  //这里不用all()，用selectd()也一样

        //遍历结果对象数组
        foreach ($result as $data){
            dump($data->getData());
        }
    }
    public function index5(){
        //**任务4：**软删除表中年龄大于30,并且工资在4000到5000之间的记录
        //创建删除条件:闭包
        $where = function ($query){
            $query -> where('id','>',1023)
                -> where('salary','between',[2000,3500]);
        };

        //软删除age>30 AND salary在4000到5000之间的记录
        $affected = Staff::destroy($where,false);

        echo $affected ? '成功软删除'.$affected.'条记录!' : '软删除失败';

        //创建闭包查询函数
        $closure = function ($query){
            $query -> field('id,name,delete_time');
        };

        //执行查询
        $result = Staff::all($closure);

        //遍历结果对象数组
        foreach ($result as $data){
            dump($data->getData());
        }
    }

    //5.restore恢复数据
    public function index6(){
        $where = [
            'id'=>['between',[1032,1035]],
        ];
        $where = [
            'id'=>['in',[1032,1034]],
        ];

//        $affected = (new Staff)->restore(['id'=>1004]);
        $affected = (new Staff)->restore($where);

        echo $affected ? '成功恢复'.$affected.'条记录!' : '恢复失败';
    }

}